package ball.sneaker.Server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;

/**
 *
 * @author Arthur
 */
public class MyHttpHandler implements HttpHandler {

    /**
     * logger
     */
    static private Logger logger;

    static {
        logger = Logger.getLogger("SystemLog");
    }

    public void handle(HttpExchange t) throws IOException {
        try {


            InputStream is = t.getRequestBody();

            String req = "";

            while (true) {
                int n = is.available();
                byte buffer[] = new byte[n];
                if (is.read(buffer, 0, n) == -1) {
                    break;
                }
                req += new String(buffer);

            }

            logger.info("Request received:\n" + req);

            String urlString = req.split("\n")[0].split("\\ ")[1];
            URL url = new URL(urlString);
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.connect();
            InputStream remoteIs = con.getInputStream();

            for (String h : con.getHeaderFields().keySet()) {
                logger.info("HEADER - " + h + ": " + con.getHeaderFields().get(h));
            }
            int rCode = Integer.parseInt(con.getHeaderFields().get(null).get(0).split("\\ ")[1]);
            logger.info("CODE: " + rCode);
//        t.sendResponseHeaders(con.getHeaderFieldInt(, 404), );

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int c;
            while ((c = remoteIs.read())!=-1) {
                baos.write(c);
            }

//            logger.info("BODY:\n" + baos.toString());

//        t.getResponseHeaders().putAll(con.getHeaderFields());
            t.sendResponseHeaders(rCode, baos.size());
            OutputStream os = t.getResponseBody();
            os.write(baos.toByteArray());
            os.flush();
            os.close();
        } catch (Throwable te) {
            te.printStackTrace();
        }
    }
}
